package com.lzl.artisan.controller;

import cn.hutool.core.lang.UUID;
import com.google.code.kaptcha.Producer;
import com.lzl.artisan.common.Const;
import com.lzl.artisan.model.Result;
import com.lzl.artisan.model.User;
import com.lzl.artisan.model.dto.LoginDto;
import com.lzl.artisan.service.UserService;
import com.lzl.artisan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private Producer producer;

    @Autowired
    private RedisCache redisCache;

    @PostMapping("login")
    public Result login(@RequestBody LoginDto loginDto){
        return userService.login(loginDto,true);
    }

    @PostMapping("register/{token}/{code}")
    public Result register(@Validated @RequestBody User user,@PathVariable String token,@PathVariable String code){
        return userService.register(user,token,code);
    }

    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = producer.createText();
        String key = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中
        redisCache.setCacheMapValue(Const.CAPTCHA_KEY, key, code, 120);
        System.out.println(key+"----"+code);

        Map<String,Object> map = new HashMap<>();
        map.put("token", key);
        map.put("base64Img", base64Img);

        return Result.ok(map);
    }
}
